package ar.sql;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import ar.globals.Globals;
import arserver.pojo.RegistrationItem;

public class RouteDatabaseHandler extends SQLiteOpenHelper {

	private static String DB_PATH = "/data/data/ar.activity/databases/";
	private static String DB_NAME = "friendRoute";

	private SQLiteDatabase myDataBase;
	private final Context myContext;

	// Locations table name
	private static final String TB_LOCATIONS = "locations";

	// Locations Table Columns names
	private static final String KEY_ID = "id";
	private static final String KEY_PHONE = "phone";
	private static final String KEY_NKNME = "nickname";
	private static final String KEY_LAT = "latitude";
	private static final String KEY_LNG = "longitude";
	private static final String KEY_DES = "description";

	public RouteDatabaseHandler(Context context) {

		super(context, DB_NAME, null, 1);
		this.myContext = context;
	}

	public void createDataBase() throws IOException {
		boolean dbExist = checkDataBase();
		if (dbExist) {
		} else {
			this.getReadableDatabase();
			try {
				copyDataBase();
			} catch (IOException e) {
				throw new Error("Error copying database");
			}
		}
	}

	private boolean checkDataBase() {
		SQLiteDatabase checkDB = null;
		try {
			String myPath = DB_PATH + DB_NAME;
			checkDB = SQLiteDatabase.openDatabase(myPath, null,
					SQLiteDatabase.OPEN_READONLY);
		} catch (SQLiteException e) {
		}

		if (checkDB != null) {
			checkDB.close();
		}
		return checkDB != null;
	}

	private void copyDataBase() throws IOException {
		InputStream myInput = myContext.getAssets().open(DB_NAME);
		String outFileName = DB_PATH + DB_NAME;
		OutputStream myOutput = new FileOutputStream(outFileName);

		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}
		myOutput.flush();
		myOutput.close();
		myInput.close();
	}

	public void openDataBase() throws SQLException {

		String myPath = DB_PATH + DB_NAME;
		myDataBase = SQLiteDatabase.openDatabase(myPath, null,
				SQLiteDatabase.OPEN_READONLY);
	}

	@Override
	public synchronized void close() {
		if (myDataBase != null)
			myDataBase.close();
		super.close();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}

	public void add(RegistrationItem reg) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(KEY_ID, String.valueOf(System.currentTimeMillis()));
		values.put(KEY_PHONE, reg.getSrcPhoneNumber());
		values.put(KEY_NKNME, reg.getSrcName());
		values.put(KEY_LAT, reg.getLat());
		values.put(KEY_LNG, reg.getLng());
		values.put(KEY_DES, Globals.routeDesc);

		db.insert(TB_LOCATIONS, null, values);
		db.close();
	}

	public List<ShareRoutePoint> getAllByDesc(String desc) {
		List<ShareRoutePoint> listRoutePoint = new ArrayList<ShareRoutePoint>();
		// Select All Query
		String selectQuery = "SELECT  * FROM " + TB_LOCATIONS
				+ " WHERE description = '" + desc + "'";

		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);

		// looping through all rows and adding to list
		if (cursor.moveToFirst()) {
			do {
				ShareRoutePoint point = new ShareRoutePoint();
				point.setSrcPhoneNumber(cursor.getString(1));
				point.setSrcName(cursor.getString(2));
				point.setLat(cursor.getString(3));
				point.setLng(cursor.getString(4));
				point.setDesc(cursor.getString(5));

				listRoutePoint.add(point);
			} while (cursor.moveToNext());
		}
		return listRoutePoint;
	}

	public List<ShareRoutePoint> getAll() {
		List<ShareRoutePoint> listRoutePoint = new ArrayList<ShareRoutePoint>();
		// Select All Query
		String selectQuery = "SELECT  * FROM " + TB_LOCATIONS;

		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);

		// looping through all rows and adding to list
		if (cursor.moveToFirst()) {
			do {
				ShareRoutePoint point = new ShareRoutePoint();
				point.setSrcPhoneNumber(cursor.getString(1));
				point.setSrcName(cursor.getString(2));
				point.setLat(cursor.getString(3));
				point.setLng(cursor.getString(4));
				point.setDesc(cursor.getString(5));

				listRoutePoint.add(point);
			} while (cursor.moveToNext());
		}
		return listRoutePoint;
	}

	public boolean clearAll() {
		List<ShareRoutePoint> l = getAll();
		SQLiteDatabase db = this.getWritableDatabase();
		int c = db.delete(TB_LOCATIONS, "1", null);
		db.close();
		return c == l.size();
	}
}
